package day03;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet5.JakartaServletFileUpload;
import util.JdbcUtil;

import java.io.IOException;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.service()");
        String path = request.getServletPath();

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        System.out.println("path = " + path);

        if ("/add.emp".equals(path)) {
            add(request, response);
        }

        if("/list.emp".equals(path)){
            list(request,response);
        }

        if("/remove.emp".equals(path)){
            remove(request,response);
        }

        if("/load.emp".equals(path)){
            load(request,response);
        }

        if("/modify.emp".equals(path)){
            modify(request,response);
        }

        if("/uploadphoto.emp".equals(path)){
            uploadphoto(request,response);
        }

    }

    protected void uploadphoto(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.uploadphoto()");
        Connection con=null;
        PreparedStatement ps=null;
        try{
            ServletContext application=getServletContext();
            String uploadDir=application.getRealPath("photo");

            DiskFileItemFactory factory=DiskFileItemFactory
                    .builder()
                    .get();


            JakartaServletFileUpload fileUpload=new JakartaServletFileUpload(factory);

            Map<String,List<FileItem>> formItemMap=fileUpload.parseParameterMap(request);

            Integer id=Integer.parseInt(formItemMap.get("id").get(0).getString());

            FileItem fileItem=formItemMap.get("photo").get(0);

            String contentType=fileItem.getContentType();
            if(!contentType.startsWith("image/")){
                request.setAttribute("message","头像必须上传图片");
                request.getRequestDispatcher("/emp/uploadphoto.jsp").forward(request,response);
                return;
            }
            long size=fileItem.getSize();
            if(size>(25*1024)){
                request.setAttribute("message","头像图片大小小于25k");
                request.getRequestDispatcher("/emp/uploadphoto.jsp").forward(request,response);
                return;
            }

            String fileName=fileItem.getName();
            String photoName=""+id+new Date().getTime()+fileName.substring(fileName.lastIndexOf("."));

            fileItem.write(Paths.get(uploadDir,photoName));




            con=JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("update t_emp ")
                    .append("set photo=? ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,photoName);
            ps.setInt(2,id);

            ps.executeUpdate();


            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }



        response.sendRedirect(request.getContextPath()+"/list.emp");


    }


    protected void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.modify()");

        Integer id=Integer.parseInt(request.getParameter("id"));
        String name=request.getParameter("name");
        String salaryStr=request.getParameter("salary");
        Double salary=salaryStr==null||"".equals(salaryStr.trim())
                ?null
                :Double.parseDouble(salaryStr);
        String sex=request.getParameter("sex");
        String eduStr=request.getParameter("edu");
        String edu="-1".equals(eduStr)
                ?null
                :eduStr;
        String[] hobbiesArr=request.getParameterValues("hobbies");
        String[] hobbies=hobbiesArr==null
                ?new String[]{}
                :hobbiesArr;
        String description=request.getParameter("description");

        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("update t_emp ")
                    .append("set name=?, ")
                    .append("    salary=?, ")
                    .append("    sex=?, ")
                    .append("    edu=?, ")
                    .append("    hobbies=?, ")
                    .append("    description=? ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,name);
            ps.setDouble(2,salary);
            ps.setString(3,sex);
            ps.setString(4,edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6,description);
            ps.setInt(7,id);

            ps.executeUpdate();


            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }

        response.sendRedirect(request.getContextPath()+"/list.emp");
    }


    protected void load(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.load()");

        Integer id=Integer.parseInt(request.getParameter("id"));

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        Emp emp=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_emp ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setInt(1,id);

            rs=ps.executeQuery();

            if(rs.next()){
                emp=new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setSex(rs.getString("sex"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                emp.setDescription(rs.getString("description"));
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

        request.setAttribute("emp",emp);

        request.getRequestDispatcher("/emp/modify.jsp").forward(request,response);
    }



    protected void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.remove()");

        Integer id=Integer.parseInt(request.getParameter("id"));

        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("delete from t_emp ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setInt(1,id);

            ps.executeUpdate();


            con.commit();

        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }
        response.sendRedirect(request.getContextPath()+"/list.emp");
    }


    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.list()");

//        int i=1/0;

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        List<Emp> emps=new ArrayList<>();

        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_emp ")
                    .toString();

            ps=con.prepareStatement(sql);

            rs=ps.executeQuery();

            while(rs.next()){
                Emp emp=new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setPhoto(rs.getString("photo"));

                emps.add(emp);
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

        request.setAttribute("emps",emps);

        request.getRequestDispatcher("/emp/list.jsp").forward(request,response);
//        response.sendRedirect(request.getContextPath()+"/emp/list.jsp");//错

    }


        protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("EmpServlet.add()");

        String name=request.getParameter("name");
        String salaryStr=request.getParameter("salary");
        Double salary=salaryStr==null||"".equals(salaryStr.trim())
                ?null
                :Double.parseDouble(salaryStr);
        String sex=request.getParameter("sex");
        String eduStr=request.getParameter("edu");
        String edu="-1".equals(eduStr)
                ?null
                :eduStr;
        String[] hobbiesArr=request.getParameterValues("hobbies");
        String[] hobbies=hobbiesArr==null
                ?new String[]{}
                :hobbiesArr;
        String description=request.getParameter("description");


        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("insert into t_emp ")
                    .append("    (name,salary,sex,edu,hobbies,description) ")
                    .append("values ")
                    .append("    (?,?,?,?,?,?) ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,name);
            ps.setDouble(2,salary);
            ps.setString(3,sex);
            ps.setString(4,edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6,description);

            ps.executeUpdate();


            con.commit();

        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }

        response.sendRedirect(request.getContextPath()+"/list.emp");
//        request.getRequestDispatcher("/list.emp").forward(request,response);

    }


}